let ip = require('../util/ipUtil');
let csv = require('../util/csvUtil');
let pc = require('../util/phoneCode');
const { BusiError, SysError } = require('../exception/exception');

let assert = require('assert');

let countryPhoneCodeService = module.exports;

let geoIpData = null;

/*
["116.60.0.0","116.63.255.255","1950089216","1950351359","CN","China"]
 */
function binarySearch(arr, key) {
    let low = 0;
    let high = arr.length - 1;
    while(low <= high){
        let mid = parseInt((high + low) / 2);
        if(key >= arr[mid][2] && key <= arr[mid][3]){
            return  arr[mid];
        }else if(key > arr[mid][3]){
            low = mid + 1;
        }else if(key < arr[mid][2]){
            high = mid -1;
        }else{
            return null;
        }
    }
}

countryPhoneCodeService.getCountryCodeByIp = async function (ipStr) {
    try {
        if (!geoIpData){
            geoIpData = await csv.parseCSV("../file/GeoIP-108.csv");
        }

        let ipLong = ip.toLong(ipStr);
        let final = parseInt(ipLong);
        if (final < 16777216) {
            throw "ip " + ipStr + " err:" + ipLong + " < 16777216 ==> 1.0.0.0";
        }

        let res = binarySearch(geoIpData, ipLong);
        if (res){
            console.logw("ip:", ipStr, "locate country:", res, "country phone code:", pc[res[4]])
            return pc[res[4]];
        }
    }catch (e) {
        console.logw("getCountryCodeByIp err:", e);
    }
    return null;
};

console.logw("phone code init:", countryPhoneCodeService.getCountryCodeByIp("127.0.0.1"));